/**
 * Created by zhongwei on 2024/09/29.
 */

/**
 * 随机获取年月日
 */
function isLeapYear(year) {
  return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0
}

function getDaysInMonth(year, month) {
  const monthDays = [31, isLeapYear(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  return monthDays[month - 1]
}

function getRandomDay(year, month) {
  const daysInMonth = getDaysInMonth(year, month)
  return Math.floor(Math.random() * daysInMonth) + 1
}

const rNum = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

export function generateRandomDate(minYear = 1924, maxYear = 2004) {
  const year = Math.floor(Math.random() * (maxYear - minYear + 1)) + 1924
  const month = Math.floor(Math.random() * 12) + 1
  const day = getRandomDay(year, month)
  return { year, month, day }
}
export function random() {
  let arr = [1, 2]
  let num = Math.floor(Math.random() * arr.length)
  return arr[num]
}

export function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms)
  })
}

export function genNum() {
  return Math.floor(Math.random() * 3023)
}

export async function prohibitWebpage(page) {
  await page.evaluate(() => {
    document.addEventListener('contextmenu', (event) => event.preventDefault())
    // 禁用键盘快捷键
    // 禁用特定的快捷键
    document.addEventListener('keydown', (event) => {
      // 检测按键组合
      if (
        (event.ctrlKey && event.key === 'u') || // Ctrl+U
        (event.ctrlKey && event.shiftKey && event.key === 'I') || // Ctrl+Shift+I
        (event.ctrlKey && event.shiftKey && event.key === 'J') || // Ctrl+Shift+J
        event.key === 'F12' || // F12
        (event.ctrlKey && event.key === 'N')   //屏蔽 Ctrl+n
      )
        {
        event.preventDefault()
        event.stopPropagation()
      }
    })
  })
}

// 监听用户长时间无操作
export async function detectInactivity(page,data) {
  await page.evaluate((result) => {
    let timeoutDuration = 2000 // 无操作超时时间，单位为毫秒，例：1分钟
    let timeoutId
    
    // 重置计时器函数
    function resetTimer() {
      clearTimeout(timeoutId)
      timeoutId = setTimeout(onInactive, timeoutDuration)
    }

    // 无操作时的处理函数
     function  onInactive() {
      console.log('页面长时间没有操作')
      console.log(result)
      result.browser()
      // 可以在这里执行需要的逻辑，比如弹出提示框或自动登出
    }

    // 监听用户的操作事件
    function setupInactivityTimer() {
      document.addEventListener('mousemove', resetTimer)
      document.addEventListener('keydown', resetTimer)
      document.addEventListener('mousedown', resetTimer) // 包括鼠标点击
      document.addEventListener('scroll', resetTimer)
      document.addEventListener('touchstart', resetTimer) // 包括触摸屏幕的操作

      resetTimer() // 初始化计时器
    }

    // 初始化监控
    setupInactivityTimer()
  },data)
}